<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>improvedThrottle</title>
  </head>
  <body>
    <input type="text" id="input" />
    <script type="text/javascript">
      input.oninput = throttle(inputTest, 500, (value) => {
        console.log(value);
      });

      function inputTest() {
        return this.value;
      }

      function throttle(fn, delay, callback) {
        var t = null,
          // 获取到节流函数绑定时的时间戳
          begin = new Date().getTime();

        var throttled = function () {
          var _self = this,
            args = arguments,
            now = new Date().getTime();

          // 清除上一次绑定的延迟事件
          // 本次触发会再次绑定
          clearTimeout(t);

          if (now - begin > delay) {
            // 当前触发时间与上次触发时间之差大于延迟时间
            // 直接响应事件
            callback(fn.apply(_self, args));
            begin = now;
          } else {
            t = setTimeout(function () {
              callback(fn.apply(_self, args));
            }, delay);
          }
        };

        throttled.remove = function () {
          clearTimeout(t);
          t = null;
        };
        return throttled;
      }
    </script>
  </body>
</html>
